package com.strongbj.iot.devices.smarrack.response.handle;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.device.Device;
import com.strongbj.core.device.DeviceManager;
import com.strongbj.core.message.MessageHandleContext;
import com.strongbj.iot.devices.smarrack.message.SmarRackMessage;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * SmarRack应答消息的处理上下文类
 * 
 * @author yuzhantao
 *
 */
public class SmarRackResponseHandleContext extends SimpleChannelInboundHandler<SmarRackMessage> {
	private static Logger logger = LogManager.getLogger(SmarRackResponseHandleContext.class.getName());
	private MessageHandleContext<SmarRackMessage, Object> messageHandleContext;

	public SmarRackResponseHandleContext() {
		super();
		try {
			this.messageHandleContext = new MessageHandleContext<>();
			this.messageHandleContext.addHandleClass(new HeartbeatHandle()); // 心跳处理
			this.messageHandleContext.addHandleClass(new UploadUInfoHandle()); // 处理上传U位信息数据
			this.messageHandleContext.addHandleClass(new UploadRackInfoHandle()); // 处理上传机架信息数据
			this.messageHandleContext.addHandleClass(new SetLedResultHandle()); // 回复设置电灯命令
		} catch (Exception e) {
			logger.error("",e);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		logger.info("数码人设备已连接{}", ctx.channel().remoteAddress().toString());

		String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
		Device dev = new Device("", ip);
		DeviceManager.getInstance().registerDevice(dev);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		logger.info("数码人设备已断开{}", ctx.channel().remoteAddress().toString());

		String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
		DeviceManager.getInstance().unregisterDevice(ip);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, SmarRackMessage msg) throws Exception {
		if (msg == null)
			return;
//		InetSocketAddress client = (InetSocketAddress) ctx.channel().remoteAddress();
		this.messageHandleContext.handle(ctx, msg); // 处理SmarRack消息
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
		logger.error(ip, cause);
		if (ctx.channel().isActive())
			ctx.close();
	}
}
